package com.peaker.advertisingpro.activity

import android.content.Context
import android.content.Intent
import android.graphics.*
import android.graphics.pdf.PdfRenderer
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.os.ParcelFileDescriptor
import android.provider.MediaStore
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.peaker.advertisingpro.R
import com.peaker.advertisingpro.entity.ViewSetObject
import com.peaker.advertisingpro.utils.NewShowViewUtils
import kotlinx.android.synthetic.main.activity_p_d_f.*
import java.io.File
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException


class PDFActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_p_d_f)


    }

    private fun tezxe() {
        var pdfToBitmap = pdfToBitmap(File("/sdcard/a.pdf"))

//        saveImageToGallery(this, pdfToBitmap(File("/sdcard/Android/a.pdf"))!!)
        var viewSetObject = ViewSetObject(this, root)
        viewSetObject.bitmap = pdfToBitmap!![0]
        viewSetObject.topMargin = 400
        viewSetObject.height=1000
        viewSetObject.type="pdf"
        NewShowViewUtils.newImageView(viewSetObject)
    }

    private fun pdfToBitmap(pdfFile: File): ArrayList<Bitmap>? {
        val bitmaps: ArrayList<Bitmap> = ArrayList()
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                val renderer = PdfRenderer(
                    ParcelFileDescriptor.open(
                        pdfFile,
                        ParcelFileDescriptor.MODE_READ_ONLY
                    )
                )
                var bitmap: Bitmap
                val pageCount = renderer.pageCount
                Log.e("test_sign", "图片de 张数： $pageCount")
                for (i in 0 until pageCount) {
                    val page = renderer.openPage(i)
                    val width = resources.displayMetrics.densityDpi / 72 * page.width
                    val height = resources.displayMetrics.densityDpi / 72 * page.height
                    bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)

                    //todo 以下三行处理图片存储到本地出现黑屏的问题，这个涉及到背景问题
                    val canvas = Canvas(bitmap)
                    canvas.drawColor(Color.WHITE)
                    canvas.drawBitmap(bitmap, 0f, 0f, null)
                    val r = Rect(0, 0, width, height)
                    page.render(bitmap, r, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY)
                    bitmaps.add(bitmap)
                    // close the page
                    page.close()
//                    System.gc()
                }
                // close the renderer
                renderer.close()
            }
        } catch (ex: Exception) {
            ex.printStackTrace()
        }
        return bitmaps
    }

    private fun saveImageToGallery(context: Context, bitmaps: ArrayList<Bitmap>) {
        // 首先保存图片
        val appDir = File(
            Environment.getExternalStorageDirectory()
                .getAbsolutePath() + File.separator.toString() + "dearxy"
        )
        for (i in 0 until bitmaps.size) {
            if (!appDir.exists()) {
                appDir.mkdir()
            }
            val fileName = System.currentTimeMillis().toString() + ".jpg"
            val file = File(appDir, fileName)
            Log.e("test_sign", "图片全路径localFile = " + appDir.absolutePath.toString() + fileName)
            var fos: FileOutputStream? = null
            try {
                fos = FileOutputStream(file)
                bitmaps[i].compress(Bitmap.CompressFormat.JPEG, 100, fos)
                fos.flush()
                fos.close()
            } catch (e: FileNotFoundException) {
//                showToast("保存到相册失败！");
                e.printStackTrace()
            } catch (e: IOException) {
//                showToast("保存到相册失败！");
                e.printStackTrace()
            } finally {
                if (fos != null) {
                    try {
                        fos.close()
                        //回收
                        bitmaps[i].recycle()
                    } catch (e: IOException) {
                        e.printStackTrace()
                    }
                }
            }
            // 其次把文件插入到系统图库
            try {
                MediaStore.Images.Media.insertImage(
                    context.getContentResolver(),
                    file.absolutePath, fileName, null
                )
            } catch (e: FileNotFoundException) {
//                showToast("保存到相册失败！");
                e.printStackTrace()
            }
        }
        //        showToast("已保存到手机相册！");
        // 最后通知图库更新
        sendBroadcast(
            Intent(
                Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                Uri.fromFile(File(appDir.path))
            )
        )
    }

    fun clickTv(view: View) {
//        tezxe()
        startActivity(Intent(this,ScrollActivity::class.java))
    }

}